﻿using System;
using System.Data.Linq;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using ConsolidationTool.Common;
using ConsolidationTool.Common.Entities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
namespace ConsolidationTool.WebParts.ControlTemplates
{
    public partial class CommonEntitySelector : FSUserControlBase
    {
        public string Actual_LoadingFileListName { get; set; }
        public string Mode { get; set; }

        public bool LockSubRegion { get { return !(Request["locksubregion"] + "").IsNullOrEmpty(); } }
        public bool LockEntity { get { return !(Request["lockentity"] + "").IsNullOrEmpty(); } }
        public string ManualMonth { get { return Request["headermonth"]; } }

         
        protected void Page_Load(object sender, EventArgs e)
        {
            OutputReport.Visible = ReportMode;
            Actual_LoadingFileListName = Constants.Actual_LoadingFileListName;


            region_DataSource = BusinessService.getRegion();//;.Where(p => p.Group.ContainsCurrentUser).ToList();
            subRegion_DataSource = BusinessService.getSubRegion();//.Where(p => p.Group.ContainsCurrentUser).ToList();
            entity_DataSource = BusinessService.getEntity();//.Where(p => p.Group.ContainsCurrentUser).ToList();


            if (IsPostBack) return;


            if (Mode == "JustEntity")
            {
                entityDataBind(entity_DataSource.Where(p => p.Groups.First().ContainsCurrentUser).ToList());
                regionArea.Visible = false;
                subRegionArea.Visible = false;
                yearTextBox.Text = DateTime.Now.Year + "";
                monthTextBox.Text = DateTime.Now.Month+"";
                return;
            }

            yearTextBox.Text = Common.BusinessService.GetConfiguration(Constants.Flash_Input_Year);
            monthTextBox.Text = Common.BusinessService.GetConfiguration(Constants.Flash_Input_Month); 

            if (!ManualMonth.IsNullOrEmpty())
            {
                monthTextBox.Text = ManualMonth;
                monthTextBox.Enabled = false;
            }
            drpSubRegion.Enabled = !LockSubRegion;
            drpEntity.Enabled = !LockEntity;

            regionDataBind(region_DataSource);

            if (SPContext.Current.List != null && (SPContext.Current.List.Title.StartsWith("R_") || Utilities.ManualStartLists.Contains(SPContext.Current.List.Title)))
            { 
                LoadRegionMerge();
                InitMergeBaseInformation();
                return;
            }
            if (Page is FSReportBase && FSReportPage.isMerge)
            {
                InitMergeBaseInformation();
                return;
            }
            subRegionDataBind(subRegion_DataSource.Where(p => p.regionName == drpRegion.SelectedValue));
            entityDataBind(entity_DataSource); 
        }

        private void LoadRegionMerge()
        {
            var objControl = RArea.FindControl("regionMerge");
            if (objControl == null)
            {
                objControl = Page.LoadControl(@"~/_CONTROLTEMPLATES/ConsolidationTool.WebParts/RegionMergeControl.ascx"); 
                objControl.ID = "regionMerge";
                RArea.Controls.Add(objControl);
                RArea.Visible = true;
            }

            var regionMerge = RArea.FindControl("regionMerge") as RegionMergeControl;
            regionMerge.SelectedRegion = drpRegion.SelectedValue;
        }

        public void InitMergeBaseInformation() 
        { 
            subRegionArea.Visible = false;
            entityArea.Visible = false;

            var selectedRegion = region_DataSource.FirstOrDefault(p => p.groupName == drpRegion.SelectedValue);
            lbCompanyCurrency.Text = selectedRegion.Currency;
            lbCompanyTonnage.Text = selectedRegion.Tonnage;
          //  lbCoCd.Text = selectedRegion.groupName;
            lbCompanyFullName.Text = selectedRegion.groupName;
        }

        public void regionDataBind(IEnumerable<Region> region)
        {
            drpRegion.DataSource = region;
            drpRegion.DataValueField = "regionName"; drpRegion.DataTextField = "regionName";
            drpRegion.DataBind();

            drpRegion.SelectedIndex = 0;
        }

        public void subRegionDataBind(IEnumerable<SubRegion> subregion)
        {
            drpSubRegion.DataSource = subregion;
            drpSubRegion.DataValueField = "subRegionName"; drpSubRegion.DataTextField = "subRegionName";
            drpSubRegion.DataBind();
            drpSubRegion.Items.Insert(0, new ListItem("(None)", "0"));
        }

        public void entityDataBind(IEnumerable<Entity> entity)
        {
            drpEntity.DataSource = entity;
            drpEntity.DataValueField = "CoCd"; drpEntity.DataTextField = "entityName";
            drpEntity.DataBind();
            drpEntity.Items.Insert(0, new ListItem("(None)", "0"));
        }

        public delegate void EntitySelectorChangeHandler(object sender, int EntityID);
        public event EntitySelectorChangeHandler EntitySelectorChanged;

        public delegate void OutputButtonClickHandler(object sender, EventArgs e);
        public event OutputButtonClickHandler OutputButtonClicked;

        public List<Region> region_DataSource = new List<Region>();
        public List<SubRegion> subRegion_DataSource = new List<SubRegion>();
        public List<Entity> entity_DataSource = new List<Entity>();

        public void drpRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (sender is string)
                drpRegion.SelectedValue = sender.ToString();

            subRegionDataBind(subRegion_DataSource.Where(p => p.regionName == drpRegion.SelectedValue));

            drpEntity.Items.Clear();
            drpEntity.Items.Insert(0, new ListItem("(None)", "0"));
        }

        public void drpSubRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (sender is string)
                drpSubRegion.SelectedValue = sender.ToString();

            var currentRegion = region_DataSource.Where(p => p.regionName == drpRegion.SelectedValue).FirstOrDefault();//Region
            var currentSubRegion = subRegion_DataSource.Where(p => p.subRegionName == drpSubRegion.SelectedValue).FirstOrDefault();//SubRegion

            List<Entity> CurrentSelectEntityList = new List<Entity>();
            if (currentRegion.Group.ContainsCurrentUser)//Current root region contain curent user
            {
                CurrentSelectEntityList = entity_DataSource.Where(p =>
                    //  p.RegionName == currentRegion.regionName
                    p.subRegionName == currentSubRegion.subRegionName
                ).ToList();
            }
            else if (currentSubRegion.Group.ContainsCurrentUser)
            { //Current sub region contain curent user 
                CurrentSelectEntityList = entity_DataSource.Where(p =>
                    p.subRegionName == currentSubRegion.subRegionName
                ).ToList();
            }
            else
            {

                CurrentSelectEntityList = entity_DataSource.Where(p =>
                    p.subRegionName == drpSubRegion.SelectedValue && p.ContainsCurrentUser //Promission
                ).ToList();
            }
            entityDataBind(CurrentSelectEntityList);

            lbCoCd.Text = "";
            lbCompanyFullName.Text = "";
            lbCompanyCurrency.Text = "";
            lbCompanyTonnage.Text = "";
        }

        public void drpEntity_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (sender is string)
                drpEntity.SelectedValue = sender.ToString();

            lbCoCd.Text = drpEntity.SelectedValue;
            lbCompanyFullName.Text = drpEntity.SelectedItem.Text;
            SelectedEntity = entity_DataSource.FirstOrDefault(p => p.CoCd == drpEntity.SelectedValue);

            HFCompanyFullName.Value = SelectedEntity.EntityFullName;

            lbCompanyCurrency.Text = SelectedEntity.Currency;
            lbCompanyTonnage.Text = SelectedEntity.Tonnage;

            if (EntitySelectorChanged != null)
                EntitySelectorChanged(sender, int.Parse(drpEntity.SelectedValue));


        }

        protected void ExportReport_Click(object sender, EventArgs e)
        {
            if (OutputButtonClicked != null)
                OutputButtonClicked(sender, e);
        }


    }
}
